using System;
using System.Diagnostics;
using System.Net;
using System.Security.Principal;
using BuildBox.Core;
using BuildBox.Core.Extensions;
using BuildBox.Core.Server;
using BuildBox.Core.SourceControl;

namespace BuildBox.Server
{
    public class BuildBoxServer : IDisposable
    {
        private readonly IConfiguration _configuration;
        private readonly IWindowsIdentityAdapter _identity;

        public BuildBoxServer(IConfiguration configuration, IHttpServer httpServer, IWindowsIdentityAdapter identity)
        {
            _configuration = configuration;
            Server = httpServer;
            _identity = identity;
        }

        public IHttpServer Server
        {
            get;
            private set;
        }

        public void Start()
        {
            Server.Start();
            //SvnProvider provider = new SvnProvider("http://autofac.googlecode.com/svn/trunk/", @"g:\temp", null, null);
            //provider.Initialize();
        }

        public void Stop()
        {
            Server.Stop();
        }

        public void Dispose()
        {
            if (Server != null)
            {
                Server.Stop();
                Server.Dispose();
            }
        }

        public void SetupForNonAdmin()
        {
            string virtualDir = _configuration.VirtualDirectory + (_configuration.VirtualDirectory.EndsWith("/") ? string.Empty : "/");
            string listenOn = "http://+:{0}{1}".FormatWith(_configuration.Port, virtualDir);
            if (CanStartListener(listenOn))
            {
                return;
            }

            Console.WriteLine("Grant rights to http");
            string processArgs = @"http add urlacl url={0} user=""{1}""".FormatWith(listenOn, _identity.Name);
            Process process = Process.Start(new ProcessStartInfo
                                                {
                                                    Verb = "runas",
                                                    Arguments = processArgs,
                                                    FileName = "netsh",
                                                });
            process.WaitForExit();
            if (!CanStartListener(listenOn))
            {
                Console.WriteLine("Could not start Listener for NonAdmin.");
            }
        }

        protected static bool CanStartListener(string listenOn)
        {
            try
            {
                var listener = new HttpListener();
                listener.Prefixes.Add(listenOn);
                listener.Start();
                listener.Stop();
                return true;
            }
            catch (HttpListenerException e)
            {
                // Trap Access Denied
                if (e.ErrorCode != 5)
                {
                    throw;
                }
            }

            return false;
        }
    }
}